﻿using System;
using System.Linq;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using NetFluid;
using Sito.model;
using Sito.Model;

namespace Sito.Logic
{
    internal class NewsManager : FluidController
    {
        private News show;

        public override bool Condition()
        {
            MongoCursor<News> news = Database.News.Find(Query.EQ("Link", RequestUri.Substring(1)));

            if (news.Count() > 0)
            {
                show = news.First();
                return true;
            }
            return false;
        }
		
        [Route("/admin")]
        public void Admin()
        {
            if (session("User") == null || session("User").Status != User.UserStatus.Admin)
            {
                render("Sito.View.Block", "WTF are u doing?!?!");
                return;
            }
            render("Sito.View.Admin");
        }

        [Route("/admin/deleteall")]
        public void CleanAll()
        {
            User user = session("User");
            if (user.Status != User.UserStatus.Admin)
            {
                printline("nice try");
                return;
            }

            Database.News.RemoveAll();
            printline("deleted");
        }

        [Route("/admin/delete")]
        public void Save(string id)
        {
            User user = session("User");
            if (user.Status != User.UserStatus.Admin)
            {
                printline("nice try");
                return;
            }

            Database.News.Remove(Query.EQ("Link", id));
            printline("saved");
            return;
        }

        [Route("/admin/save")]
        public void Save(string category,string title, string body)
        {
            User user = session("User");
            if (user.Status != User.UserStatus.Admin)
                return;

            if (string.IsNullOrEmpty(title))
                title = "(untitled)";

            if (string.IsNullOrEmpty(category))
                category = "News";

            string[] tags = (title + " " + body + " " + user.NiceName + " "+category).Split(' ').Select(x=>x.ToLower()).ToArray();

            var news = new News
                           {
                               Author = user.NiceName,
                               Body = body,
                               Date = DateTime.Now,
                               Link = title + rnd(9999),
                               Tags = tags,
                               Title = title,
                               Category = category
                           };
            Database.News.Save(news);
            Database.News.EnsureIndex("Tags");
        }

        public override void Main()
        {
            render("Sito.View.News", show);
        }
    }
}